import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_out_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_out.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/delivery.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/ship_the_products.dart';
import 'package:flutter_admin/pages/odoo/material/hw_check/hw_packing.dart';
import 'package:flutter_admin/pages/odoo/material/hw_check/hw_product_register.dart';
import 'package:flutter_admin/pages/odoo/material/hw_check/hw_weigh.dart';
import 'package:flutter_admin/pages/odoo/material/location_out/location_out_confirmation.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

import 'hw_check_detail.dart';
import 'hw_check_dialog.dart';
import 'hw_warehousing.dart';

class HWCheckList extends StatefulWidget {
  HWCheckList({Key? key}) : super(key: key);

  @override
  _HWCheckListState createState() => _HWCheckListState();
}

class _HWCheckListState extends State<HWCheckList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
  PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  List<StockQuant> selectedList = [];
  StockQuant stockQuant = StockQuant();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  // _loadSelectVO() async {
  //   workshopList = await DynamicDataApi.getModelSelect(
  //       model: "hr.department",
  //       name: "complete_name",
  //       key: "parent_id",
  //       operator: "!=",
  //       val: null);
  //   setState(() {});
  // }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 160,
            label: '产品编码',
            value: stockQuant.productCode,
            onSaved: (v) {
              stockQuant.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料名称',
            value: stockQuant.productName,
            onSaved: (v) {
              stockQuant.productName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '销售单号',
            value: stockQuant.saleorder,
            onSaved: (v) {
              stockQuant.saleorder = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
        _operationList(),
      ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('销售单号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('操作人')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('生产单号')),
        // DataColumn(label: Text('是否包装')),
        // DataColumn(label: Text('是否称重')),
      ],
      getCells: (m) {
        StockQuant stockQuant = StockQuant.fromHWMap(m);
        return [
          DataCell(Text(stockQuant.saleorder ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.productUomName ?? '--')),
          DataCell(Text(stockQuant.username ?? '--')),
          DataCell(Text(stockQuant.quantity.toString())),
          DataCell(Text(stockQuant.productorderno ?? '--')),
          // DataCell(Text(stockQuant.isPackaging == '1'?'是':'否')),
          // DataCell(Text(stockQuant.isWeigh == '1'?'是':'否')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: '查看明细',
            iconData: Icons.view_agenda_rounded,
            onPressed: selectedList.length == 1 && selectedList[0].internalPrintStatus == '1'  && selectedList[0].exteriorPrintStatus == '1'
                ? () => _openDetail(selectedList[0])
                : null),
        CryButton(
            label: "内标签打印",
            iconData: Icons.view_headline,
            onPressed: selectedList.length == 1  && selectedList[0].internalPrintStatus != '1'?() => {_HWPrint('internal_print', selectedList[0].id)}:null),
        CryButton(
            label: "外标签打印",
            iconData: Icons.view_headline,
            onPressed: selectedList.length == 1  && selectedList[0].exteriorPrintStatus != '1'?() => {_HWPrint('exterior_print', selectedList[0].id)}:null),
        // CryButton(
        //     label: "完成入库",
        //     iconData: Icons.view_headline,
        //     onPressed: selectedList.length == 1?() => {_confirmation(selectedList[0])}:null),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _openDetail(StockQuant stockQuant) {
    StoreUtil.write("key", "HWCheckDetail");
    Utils.fullscreenDialog(HWCheckDetail(
      huaweiCheckId: stockQuant.id!,
    ));
  }

  _HWProductRegister(){
    StoreUtil.write("key", "HWProductRegister");
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: HWProductRegister(),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _HWPrint(method, id) async{
    var res = await StockQuantOdooApi.HWprint(method,id);
    if(res.success!){
      CryUtils.message("操作成功");
      _loadData();
    }
  }

  _HWWarehousing(StockQuant stockQuant) async{
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: HWWarehousing(stockQuant: stockQuant,),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _reset() {
    stockQuant = StockQuant();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    stockQuant.isHuaweiDone = '1';
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.HWPage(
        data: {"page": page, "domainList": stockQuant.toHWDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: HWCheckDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockQuant = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<StockQuant>((e) => StockQuant.fromHWMap(e))
        .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.reset) {
          _HWProductRegister();
        } else if (v == OperationType.add) {
          _HWPrint('internal_print', selectedList[0].id);
        } else if (v == OperationType.edit) {
          _HWPrint('exterior_print', selectedList[0].id);
        } else if (v == OperationType.dmsFile) {
          _HWWarehousing(selectedList[0]);
        } else if (v == OperationType.delete){
          _openDetail(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.reset,
          child: ListTile(
            leading: const Icon(Icons.view_headline),
            title: Text('产品下线登记'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length == 1 && selectedList[0].internalPrintStatus == '1'  && selectedList[0].exteriorPrintStatus == '1',
          child: ListTile(
            enabled: selectedList.length == 1 && selectedList[0].internalPrintStatus == '1'  && selectedList[0].exteriorPrintStatus == '1',
            leading: const Icon(Icons.view_agenda_rounded),
            title: Text('查看明细'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          enabled: selectedList.length == 1  && selectedList[0].internalPrintStatus != '1',
          child: ListTile(
            leading: const Icon(Icons.view_headline),
            enabled: selectedList.length == 1 && selectedList[0].internalPrintStatus != '1',
            title: Text('内标签打印'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1  && selectedList[0].exteriorPrintStatus != '1',
          child: ListTile(
            leading: const Icon(Icons.view_headline),
            enabled: selectedList.length == 1 && selectedList[0].exteriorPrintStatus != '1',
            title: Text('外标签打印'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1 && selectedList[0].internalPrintStatus == '1'  && selectedList[0].exteriorPrintStatus == '1',
          child: ListTile(
            leading: const Icon(Icons.view_headline),
            enabled: selectedList.length == 1 && selectedList[0].internalPrintStatus == '1'  && selectedList[0].exteriorPrintStatus == '1',
            title: Text('完成入库'),
          ),
        ),
      ],
    );
  }
}
